package com.yj.auto.helper;

import java.util.List;

import org.quartz.Trigger;
import org.quartz.TriggerKey;

import com.jfinal.kit.StrKit;
import com.jfinal.log.Log;
import com.xiaoleilu.hutool.util.NetUtil;
import com.yj.auto.core.web.system.model.Schedule;
import com.yj.auto.utils.QuartzUtil;

public class ScheduleHelper {
	private static final Log logger = Log.getLog(ScheduleHelper.class);

	public static void loadSchedule() {
		List<Schedule> tasks = AutoHelper.getScheduleService().all();
		for (Schedule model : tasks) {
			addJob(model);
		}
	}

	// 是否为禁用定时任务，包括两种情况：1、运行服务器IP设置不一至；2、状态为禁用
	public static boolean isDisabled(Schedule model) {
		String serverIp = NetUtil.getLocalhostStr();
		if (StrKit.notBlank(model.getServerIp()) && !model.getServerIp().equals(serverIp)) {
			return true;// 和任务指定执行的服务器不一至,忽略
		}
		return QuartzUtil.JOB_STATE_DISABLE.equals(model.getState());
	}

	public static void addJob(Schedule model) {
		if (isDisabled(model))
			return;
		try {
			String impl = model.getImpl();
			Class jobClass = Class.forName(impl);
			QuartzUtil.me().addJob(model.getJobName(), model.getJobGroup(), model.getTriggerName(), model.getTriggerGroup(), jobClass, model.getCron());
		} catch (ClassNotFoundException e) {
			logger.error("添加定时任务失败[" + model.getCode() + "," + model.getName() + "]", e);
		}
	}

	public static void modifyJobTime(Schedule model) {
		QuartzUtil utils = QuartzUtil.me();
		if (utils.existsJob(model.getJobName(), model.getJobGroup())) {
			if (isDisabled(model)) {
				utils.removeJob(model.getJobName(), model.getJobGroup());
			} else {
				utils.modifyJobTime(model.getJobName(), model.getJobGroup(), model.getCron());
			}
		} else {
			addJob(model);
		}
	}

	public static void removeJob(Schedule model) {
		QuartzUtil.me().removeJob(model.getJobName(), model.getJobGroup());
	}

	public static void resumeJob(Schedule model) {
		QuartzUtil.me().resumeJob(model.getJobName(), model.getJobGroup());
	}

	public static void pauseJob(Schedule model) {
		QuartzUtil.me().pauseJob(model.getJobName(), model.getJobGroup());
	}

	public static void startJob(Schedule model) {
		QuartzUtil.me().startJob(model.getJobName(), model.getJobGroup());
	}

	public static String jobState(Schedule model) {
		return QuartzUtil.me().jobState(model.getTriggerName(), model.getTriggerGroup());
	}

	public static Trigger getTrigger(Schedule model) {
		TriggerKey triggerKey = QuartzUtil.getTriggerKey(model.getTriggerName(), model.getTriggerGroup());
		return QuartzUtil.me().getTrigger(triggerKey);
	}
}
